// @coding: utf8

package network

import (
	"bytes"
	"io"
	"net"
	"sync"
)

// tcp连接
type TcpConn struct {
	io.Reader // 接口类型，标识可以直接调用Read相关接口
	io.Writer
	sync.Mutex              // 标识TcpConn拥有互斥锁功能，可以直接在实例上调用Lock\Unlock
	buffer     bytes.Buffer // 临时存储
	conn       net.Conn     // 原始tcp对象
	closeFlag  bool         // 标识连接是否已经关闭
}

func newTcpConn(conn net.Conn) *TcpConn {
	tcpConn := new(TcpConn)
	tcpConn.conn = conn
	return tcpConn
}

func (tcpConn *TcpConn) doDestory() {
	tcpConn.conn.(*net.TCPConn).SetLinger(0)
	tcpConn.conn.Close()

	if !tcpConn.closeFlag {
		tcpConn.closeFlag = true
	}
}

func (tcpConn *TcpConn) Destory() {
	tcpConn.Lock()
	defer tcpConn.Unlock()
	tcpConn.doDestory()
}

func (tcpConn *TcpConn) Close() error {
	tcpConn.Lock()
	defer tcpConn.Unlock()
	if tcpConn.closeFlag {
		return nil
	}
	tcpConn.closeFlag = true
	return tcpConn.conn.Close()
}

func (tcpConn *TcpConn) Write(bytes []byte) (cnt int, err error) {
	tcpConn.Lock()
	defer tcpConn.Unlock()
	if tcpConn.closeFlag || bytes == nil {
		return
	}
	return tcpConn.conn.Write(bytes)
}
